﻿using JustMetClient.Update.Commons;
using Azylee.Core.DataUtils.StringUtils;
using Azylee.Core.DelegateUtils.ProcessDelegateUtils;
using Azylee.Core.IOUtils.DirUtils;
using Azylee.Core.IOUtils.TxtUtils;
using Azylee.Core.Plus.DataUtils.JsonUtils;
using Azylee.Core.ProcessUtils;
using Azylee.Core.VersionUtils;
using Azylee.Update.UpdateUtils;
using Azylee.YeahWeb.FTPUtils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace JustMetClient.Update.Views.MainViews
{
    public partial class MainForm : Form
    {
        string FTPIP = "", FTPAccount = "", FTPPassword = "", ASVersionPath = "", ASVersionFile = "";

        AppUpdateTool aut = new AppUpdateTool();
        AppUpdateInfo info;
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            HideForm();
            R.JustMetClientVersion = VersionTool.Format(IniTool.GetString(R.Files.Datas, "Version", "JustMetClient-Current", "0.0.0.0"));
            LBNowVersion.Text = "当前版本：" + R.JustMetClientVersion;

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);//5秒后开始更新

                if (ReadConfig())
                {
                    GetNewVersion();//查询新版本，并更新新版本
                }

                Thread.Sleep(5000);//5秒后退出程序
                CloseAndRestart();//更新后退出程序
            });
        }
        private void HideForm()
        {
            Opacity = 0;
            ShowInTaskbar = false;
            Hide();
        }
        private void ShowForm()
        {
            Opacity = 100;
            ShowInTaskbar = true;
            Show();
        }

        private bool ReadConfig()
        {
            try
            {
                string exe = IniTool.GetString(R.Files.Datas, "File", "JustMetClient.exe", "");
                if (!string.IsNullOrWhiteSpace(exe))
                {
                    FTPIP = ConfigTool.GetExe(exe, "SERVER_FTP_IP","");
                    FTPAccount = ConfigTool.GetExe(exe, "SERVER_FTP_ACCOUNT", "");
                    FTPPassword = ConfigTool.GetExe(exe, "SERVER_FTP_PASSWORD", "");
                    ASVersionPath = ConfigTool.GetExe(exe, "JustMetClient_Version_Path", "");
                    ASVersionFile = ConfigTool.GetExe(exe, "JustMetClient_Version_File", "");
                    R.Log.i("读取配置：");
                    R.Log.i("FTPIP：" + FTPIP);
                    R.Log.i("FTPAccount：" + FTPAccount);
                    R.Log.i("FTPPassword：" + FTPPassword);
                    R.Log.i("ASVersionPath：" + ASVersionPath);
                    R.Log.i("ASVersionFile：" + ASVersionFile);
                }

                //验证配置读取成功
                if (!string.IsNullOrWhiteSpace(FTPIP) &&
                    !string.IsNullOrWhiteSpace(FTPAccount) &&
                    !string.IsNullOrWhiteSpace(FTPPassword) &&
                    !string.IsNullOrWhiteSpace(ASVersionPath) &&
                    !string.IsNullOrWhiteSpace(ASVersionFile))
                    return true;
            }
            catch { }
            return false;
        }

        #region Task
        void GetNewVersion()
        {
            FtpTool ftpTool = new FtpTool(FTPIP, FTPAccount, FTPPassword);
            bool flag = ftpTool.Download(ASVersionPath + ASVersionFile, DirTool.Combine(R.Paths.Temp, "JustMetClient.version"));
            if (flag)
            {
                R.Log.i("下载版本配置文件成功");
                string s = TxtTool.Read(DirTool.Combine(R.Paths.Temp, "JustMetClient.version"));
                info = JsonTool.ToObjFromStr<AppUpdateInfo>(s);
                R.Log.i(info);

                if (info.Version != R.JustMetClientVersion.ToString())
                {
                    UIGetNewVersion(true);

                    R.Log.i("启动更新流程");
                    //启动更新流程
                    BeginInvoke(new Action(() =>
                    {
                        LBStatus.Text = "状态：正在更新...";
                        PNProgress.Visible = true;
                    }));
                    StartUpdate();
                }
                else
                {
                    info = null;
                    UIGetNewVersion(false);
                }
            }
        }
        void StartUpdate()
        {
            int fgUpdate = aut.Update(info, R.Paths.Temp, R.Paths.Relative, UIDownProgress, null, UIUnpackProgress, null);

            if (fgUpdate >= 0)
            {
                R.Log.i("指定启动版本为新版本：" + info.Version);
                IniTool.Set(R.Files.Datas, "Version", "JustMetClient-New", info.Version);
                string _nv = IniTool.GetString(R.Files.Datas, "Version", "JustMetClient-New", "-");
                R.Log.i("验证是否指定成功：" + _nv);

                UISetUpdateResult(true);
            }
            else
            {
                UISetUpdateResult(false);

                string current = DateTime.Now.ToString("yyyyMMddHH");
                string errorString = IniTool.GetString(R.Files.Datas, "Update", "Error", "");

                //如果错误日期不是当前小时，则清空错误日期记录
                if (!errorString.Contains(current)) { errorString = ""; }
                errorString += current + "|";
                IniTool.Set(R.Files.Datas, "Update", "Error", errorString);
            }
        }
        private void CloseAndRestart()
        {
            ProcessTool.Start(R.Files.Launch, "-delay5");
            BeginInvoke(new Action(() =>
            {
                Close();
                Application.Exit();
            }));
        }
        #endregion

        #region UI
        private void NIMainNotify_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowForm();
        }
        private void UIDownProgress(object sender, ProgressEventArgs e)
        {
            try
            {
                BeginInvoke(new Action(() =>
                {
                    progressBar1.Value = (int)(e.Current * 100 / e.Total);
                    LBDownload.Text = string.Format("{0} %", e.Current * 100 / e.Total);
                }));
            }
            catch { }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            HideForm();
            e.Cancel = true;
        }

        private void UIUnpackProgress(object sender, ProgressEventArgs e)
        {
            try
            {
                BeginInvoke(new Action(() =>
                {
                    progressBar2.Value = (int)(e.Current * 100 / e.Total);
                    LBRelease.Text = string.Format("{0} %", e.Current * 100 / e.Total);
                }));
            }
            catch { }
        }
        private void UIGetNewVersion(bool newVersion)
        {
            try
            {
                BeginInvoke(new Action(() =>
                {
                    if (newVersion)
                    {
                        LBNewVersion.Text = String.Format("发现新版本{0} 。是否更新？", info.Version);
                    }
                    else
                    {
                        LBNewVersion.Text = "已经是最新版本";
                    }
                }));
            }
            catch { }
        }
        private void UISetUpdateResult(bool succ)
        {
            try
            {
                BeginInvoke(new Action(() =>
                {
                    if (succ)
                    {
                        LBStatus.Text = "状态：更新成功，准备重新启动程序……";
                    }
                    else
                    {
                        LBStatus.Text = "状态：更新失败，请稍后重试";
                    }
                }));
            }
            catch { }
        }
        #endregion
    }
}
